﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="DHGMS Solutions" file="Zip.cs">
//   2004-2012 DHGMS Solutions. Some Rights Reserved. Licensed under GNU General Public License version 2 (GPLv2)
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Dhgms.TplHelper.Controller.Task.CompressFile
{
    using Dhgms.TplHelper.Model.Info.TaskResult;

    using Ionic.Zip;
    using Ionic.Zlib;

    /// <summary>
    /// Task for compressing a file into a zip file
    /// </summary>
    public class Zip : Base<RecordProcessor>
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Zip"/> class. 
        /// </summary>
        /// <param name="sourceFullFileName">
        /// File we're tranferring
        /// </param>
        /// <param name="targetFileName">
        /// Name the file will be stored as (will overwrite if it already exists)
        /// </param>
        public Zip(string sourceFullFileName, string targetFileName)
            : base("Compressing File with zip")
        {
            this.SourceFullFileName = sourceFullFileName;
            this.TargetFileName = targetFileName;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the name of the file we're tranferring
        /// </summary>
        private string SourceFullFileName { get; set; }

        /// <summary>
        /// Gets or sets the name of the file will be stored as (will overwrite if it already exists)
        /// </summary>
        private string TargetFileName { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// The OnProcess event for doing the donkey work
        /// </summary>
        /// <param name="result">
        /// object that contains result information
        /// </param>
        protected override void OnProcess(RecordProcessor result)
        {
            using (var zip = new ZipFile())
            {
                // removes folders from the zip file, so everything is in the root
                zip.AddFile(this.SourceFullFileName, string.Empty);
                zip.CompressionLevel = CompressionLevel.BestCompression;
                zip.UseZip64WhenSaving = Zip64Option.AsNecessary;
                zip.Save(this.TargetFileName);
            }

            result.RecordsProcessed = 1;
        }

        #endregion
    }
}